#include "tp2.h"

#define MIN(x,y) ( x < y ? x : y )
#define MAX(x,y) ( x > y ? x : y )

#define P 2

//dst(i,j) = min( max( src (i,j) + var (i,j) , 0 ), 255 )
//dst(i,j) = src(i,j) si i < 2 v j < 2 v i + 2 >= tamy v j + 2 >= tamx


void ldr_c    (

    unsigned char *src,
    unsigned char *dst,
    int cols,
    int filas,
    int src_row_size,
    int dst_row_size,
    int alfa

)

{

	unsigned char (*src_matrix)[src_row_size] = (unsigned char (*)[src_row_size]) src;
	unsigned char (*dst_matrix)[dst_row_size] = (unsigned char (*)[dst_row_size]) dst;
	int max = 5*5*255*3*255;
	int suma_rgb = 0;
	for (int i = 0; i < filas; i++){
        	for (int j = 0; j < cols; j++){
            		rgb_t *p_d = (rgb_t*) &dst_matrix[i][j * 3];
            		rgb_t *p_s = (rgb_t*) &src_matrix[i][j * 3];
            		if( (i<2) || (j<2) || (i+2 >= filas) || (j+2 >=cols)){
                		*p_d = *p_s;
            		}
	    		else{
                		suma_rgb = 0;
                		for(int i_aux = i-2;i_aux<=i+2;i_aux++){
                    			for(int j_aux = j-2; j_aux<= j+2;j_aux++){
                        			rgb_t *p_aux = (rgb_t*) &src_matrix[i_aux][j_aux*3];
                        			suma_rgb = suma_rgb + p_aux->b + p_aux->g + p_aux->r;
                    			}
                		}
				int var;
				//pixel rojo
				var = (p_s->r)*alfa*suma_rgb;
				var = var/max;
                		p_d->r = MIN(MAX((p_s->r) + var,0),255);
				//pixel verde
				var = (p_s->g)*alfa*suma_rgb;
				var = var/max;
                		p_d->g = MIN(MAX((p_s->g) + var,0),255);
				//pixel azul
				var = (p_s->b)*alfa*suma_rgb;
				var = var/max;
                		p_d->b = MIN(MAX((p_s->b) + var,0),255);
            		}
        	}
    	}
}
